package com.awaken.content.service.impl;

import com.awaken.content.mapper.CategoryMapper;
import com.awaken.content.models.dto.CategoryDTO;
import com.awaken.content.models.entity.Category;
import com.awaken.content.models.request.CategoryRequest;
import com.awaken.content.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    
    @Override
    public CategoryDTO createCategory(CategoryRequest request) {
        Category category = new Category();
        BeanUtils.copyProperties(request, category);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        
        save(category);
        
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
    
    @Override
    public CategoryDTO getCategoryById(Long id) {
        Category category = getById(id);
        if (category == null) {
            return null;
        }
        
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
    
    @Override
    public List<CategoryDTO> getAllCategories() {
        List<Category> categories = list();
        return categories.stream().map(category -> {
            CategoryDTO dto = new CategoryDTO();
            BeanUtils.copyProperties(category, dto);
            return dto;
        }).collect(Collectors.toList());
    }
    
    @Override
    public List<CategoryDTO> getCategoriesByParentId(Long parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Category> categories = list(queryWrapper);
        
        return categories.stream().map(category -> {
            CategoryDTO dto = new CategoryDTO();
            BeanUtils.copyProperties(category, dto);
            return dto;
        }).collect(Collectors.toList());
    }
    
    @Override
    public CategoryDTO updateCategory(Long id, CategoryRequest request) {
        Category category = getById(id);
        if (category == null) {
            return null;
        }
        
        BeanUtils.copyProperties(request, category);
        category.setUpdateTime(LocalDateTime.now());
        updateById(category);
        
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
    
    @Override
    public void deleteCategory(Long id) {
        removeById(id);
    }
} 